import 'dart:convert';

import 'package:df/utils/logger_utils.dart';
import 'package:dio/dio.dart';
import 'dart:async';
import 'package:fluwx/fluwx.dart';
import 'package:df/generated/l10n.dart';

///TODO 后端不肯做授权码之后的事情，导致的SB方案。

/// 微信登录回调。
typedef WeChatCallback = Function(WeChat response);
const int kCodeSuccess = 0;
const int kCodeErrorUnknown = -1;
const int kCodeError = 1;
/// 微信登录回调接口。
class WeChat {
  WeChat._(this.code, this.msg, this.data);

  final int code;
  final String msg;
  final String? data;
}

/// 拉起微信回调观察者。
WeChatResponseSubscriber? subscriber;
/// 【微信1/4】移动应用拉起微信授权登录(获取授权码)。https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Access_Guide/Android.html
Future<Fluwx?> wechatLogin(WeChatCallback callback) async {
  Fluwx fluwx = Fluwx();
  await fluwx.registerApi(
    appId: 'wx48ffb50922f655a0',
    doOnAndroid: true,
    doOnIOS: true,
    universalLink: 'https://pheyma.com/mobile/',
  );

  //【微信1/】是否安装微信
  var result = await fluwx.isWeChatInstalled;
  LogUtils.v('【微信登录】是否安装微信= $result');

  if (result) {
    //【微信2/】注册监听
    subscriber = (WeChatResponse response) {
      LogUtils.v("【微信登录】注册监听= ${response}");

      if (response is WeChatAuthResponse) {
        LogUtils.v('【微信登录】注册监听，回调结果：\n回调码= ${response.code} \n状态= ${response.state} \n国家= ${response.country}');

        int errCode = response.errCode!;
        String errStr = response.errStr ?? "";
        LogUtils.v("【微信登录】监听回调，错误码= ${response.errCode}");

        if (errCode == 0) {
          LogUtils.e("【微信登录】监听正常= ${response}");
          String code = response.code!;
          auth3(code).then((response) {
            callback(response);
          });
        } else if (errCode == -4) {
          LogUtils.v("【微信登录】用户拒绝授权= ${errCode}");
          callback(WeChat._(errCode, errStr, null));
        } else if (errCode == -2) {
          LogUtils.v("【微信登录】用户拒绝授权= ${errCode}");
          callback(WeChat._(errCode, errStr, null));
        } else {
          callback(WeChat._(kCodeErrorUnknown, S.current.unknownError, null));
        }

      } else {
        callback(WeChat._(kCodeErrorUnknown, S.current.unknownError, null));
      }

      if(subscriber != null) {
        fluwx.removeSubscriber(subscriber!);
      }
    };
    fluwx.addSubscriber(subscriber!);

    //【微信3/】拉起微信(并回调到第2步)
    //https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html
    ///appid 应用唯一标识
    ///scope 应用授权作用域
    ///state 用于保持请求和回调的状态，授权请求后原样带回给第三方。(url encode操作，防止特殊字符（如'#'、'&'等）)
    fluwx.authBy(
        which: NormalAuth(
          scope: 'snsapi_userinfo',//用户个人信息
          state: 'wechat_login',
        ))
        .then((isAuth) {
          LogUtils.w("【微信登录】是否授权= ${isAuth}");
        }
    );
    ///返回示例：
    // appid: wxd477edab60670232
    // scope: snsapi_userinfo
    // state: wechat_sdk_demo

    return fluwx;
  } else {
    callback(WeChat._(kCodeError, S.current.weChatNotInstalled, null));
    return null;
  }
}
///https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html
///【微信4/4】获取用户信息。GET https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
// https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Authorized_API_call_UnionID.html
//  接口	                      接口说明
// /sns/oauth2/access_token   通过code换取access_token、refresh_token和已授权scope
// /sns/oauth2/refresh_token  刷新或续期access_token使用
// /sns/auth	                检查access_token有效性
// /sns/userinfo	            获取用户个人信息
// Future<WeChat> userinfo4(String code) async {
//   return null;
// }

///微信登录【3/4】刷新access_token有效期：
/// 刷新或续期 access_token 使用：      GET https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
/// 检验授权凭证（access_token）是否有效：GET https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
Future<WeChat> auth3(String code) async {

  Response response = await getAccessToken2(code);
  LogUtils.v("【微信登录】【Token】结果= ${response.data}");
  //不合法的appid
  //{errcode: 40013, errmsg: invalid appid, rid: 65885f0f-07825774-7bab7642}
  if (response.data is String) {
    Map map = json.decode(response.data);
    //{"access_token":"75_8ARm4_xeYyF-rIY6SlKIN3CKTs3kymaoWt4Qf4x1oGzwL6ytw5oUZBcH1TQ0nx-ifJoecr_axc_jEHe5JGv1a18rT68FVMrzoCBXj--HcUw",
    // "expires_in":7200,
    // "refresh_token":"75_ogqVEonOA6KdHNpsBX_EN4ABMqmHHYSdvKzqZrNfndyw5bdIGIZ_du7cNZCTdkVkcQBxr7oH4cKi-m7Jk-oE9KnOmSMqRa52YFpAosleabI",
    // "openid":"oevQot3Tnh4TGU_nN6DRo6PdlyWE",
    // "scope":"snsapi_userinfo",
    // "unionid":"oMZGiv3XGCeU3CSQTsfvVDQsuR3Y"}
    String access_token = map["access_token"]; //接口调用凭证
    int expires_in = map["expires_in"]; //access_token 接口调用凭证超时时间，单位（秒）
    String refresh_token = map["refresh_token"]; //用户刷新 access_token
    String openid = map["openid"]; //授权用户唯一标识
    String scope = map["scope"]; //用户授权的作用域（snsapi_userinfo）
    String unionid = map["unionid"]; //当且仅当该移动应用已获得该用户的 userinfo 授权时，才会出现该字段

    LogUtils.v("【微信登录】【Token】超时时间= ${expires_in}");
    LogUtils.v("【微信登录】【Token】用户刷新= ${refresh_token}");
    LogUtils.v("【微信登录】【Token】作用域= ${scope}");
    LogUtils.v("【微信登录】【Token】凭证= ${access_token}");
    LogUtils.v("【微信登录】【Token】唯一标识= ${openid}");
    LogUtils.v("【微信登录】【Token】ID= ${unionid}");

    //
    //return WeChat._(kCodeSuccess, "成功", openid);//oDirX6SqYxMpKt_K9V12X_Q5VAUU(android)、oTCIo5gw2ABT5fPOZpSH9eOfR4UY(公众号)
    return WeChat._(kCodeSuccess, "成功", unionid);//ok-Ft6Fan2WipBocq_NzlK2Yy790
  } else {
    Map<String, dynamic> responseData = response.data;
    // 获取 errcode 和 errmsg
    int errorCode = responseData["errcode"];
    String errorMessage = responseData["errmsg"];
    String rid = responseData["rid"];
    LogUtils.v("【微信登录】【Token】错误码= ${errorCode}");
    LogUtils.v("【微信登录】【Token】错误信息= ${errorMessage}");
    LogUtils.v("【微信登录】【Token】rid= ${rid}");

    return WeChat._(errorCode, errorMessage, null);
  }
}

///https://developers.weixin.qq.com/doc/oplatform/Mobile_App/WeChat_Login/Development_Guide.html
///【微信2/4】通过code(授权码)获取access_token。GET https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
Future<Response> getAccessToken2(String code) async {

  /// 通过 code 获取 access_token
  // appid	    是   应用唯一标识，在微信开放平台提交应用审核通过后获得
  // secret	    是   应用密钥 AppSecret，在微信开放平台提交应用审核通过后获得
  // code	      是   填写第一步获取的 code 参数
  // grant_type 是   填 authorization_code
  ///返回说明-正确的返回：
  // access_token	  接口调用凭证
  // expires_in	    access_token 接口调用凭证超时时间，单位（秒）
  // refresh_token  用户刷新 access_token
  // openid	        授权用户唯一标识
  // scope	        用户授权的作用域（snsapi_userinfo）
  // unionid	      当且仅当该移动应用已获得该用户的 userinfo 授权时，才会出现该字段
  // {
  //   "access_token": "ACCESS_TOKEN",
  //   "expires_in": 7200,
  //   "refresh_token": "REFRESH_TOKEN",
  //   "openid": "OPENID",
  //   "scope": "snsapi_userinfo",
  //   "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
  // }
  // {"errcode":40029,"errmsg":"invalid code"}

  return await Dio().get(
    "https://api.weixin.qq.com/sns/oauth2/access_token",
    //?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    //应用包名：com.gzmelife.app
    //APPID：wxca3ec615b5c7533b
    //AppSecret：9de5f94b97f2dcfc472183d5cec69bb1
    //应用签名：ae15ddcd9c2ac82ea4c5374599ba21e9

    queryParameters: {
      "appid": "wx48ffb50922f655a0",//
      "secret": "e014f268f015306e43651f3691d8bafb",//
      "code": code,
      "grant_type": "authorization_code"
    },
  );
}